package com.erbadagang.springcloudalibaba.stream.rocketmq.producer.controller;

import com.alibaba.fastjson.JSONObject;
import com.erbadagang.springcloudalibaba.stream.rocketmq.producer.message.Demo01Message;
import com.erbadagang.springcloudalibaba.stream.rocketmq.producer.message.IDUtil;
import com.erbadagang.springcloudalibaba.stream.rocketmq.producer.message.MySource;
import org.apache.rocketmq.common.message.MessageConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/demo01")
@EnableBinding({MySource.class})
public class Demo01Controller {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MySource mySource;//<1>

    @GetMapping("/send")
    public boolean send() {
        // <2>创建 Message
        Integer a = new Random().nextInt();
        Demo01Message message = new Demo01Message().setId(a);
        // <3>创建 Spring Message 对象
        Message<Demo01Message> springMessage = MessageBuilder.withPayload(message).build();
        // <4>发送消息
        logger.info("发送消息成功了：" + a);
        return mySource.erbadagangOutput().send(springMessage);
    }

    @GetMapping("/send2")
    public boolean send2() {
        // <2>创建 Message
        Integer a = new Random().nextInt();
        Demo01Message message = new Demo01Message().setId(a);
        // <3>创建 Spring Message 对象
        Message<Demo01Message> springMessage = MessageBuilder.withPayload(message).build();
        // <4>发送消息
        logger.info("发送消息成功了：" + a);
        return mySource.erbadagangOutput2().send(springMessage);
    }

    /**
     * 移动审批给渠道端推送消息
     *
     * @return
     */
    @GetMapping("/sendMessageToChannel")
    public boolean sendMessageToChannel() {
        Integer a = new Random().nextInt();
        Demo01Message message = new Demo01Message().setId(a);
        Message<Demo01Message> springMessage = MessageBuilder.withPayload(message).build();
        logger.info("移动审批给渠道端推送消息：" + a);
        return mySource.sendMessageToChannel().send(springMessage);
    }

    /**
     * 渠道端推送审批消息到移动审批
     *
     * @param prevTrackId
     * @param taskId
     * @return
     */
    @GetMapping("/mqChannelApproveTest")
    public String mqChannelApproveTest(String prevTrackId, String taskId,
                                       String hasCommand, String allowApproveOperate, String commandResult, String reason, String channel, String commandName) {
        logger.info("模仿渠道端发送消息=========================Start");
        Map<String, Object> msgMap = new HashMap<>(16);
        msgMap.put("traceId", IDUtil.getSecureRandomId());
        msgMap.put("prevTraceId", prevTrackId);
        msgMap.put("requestTime", LocalDateTime.now());
        msgMap.put("channel", channel);
        msgMap.put("commandName", commandName);
        msgMap.put("reason", reason);
        msgMap.put("taskId", taskId);

        msgMap.put("hasCommand", "1".equals(hasCommand));
        msgMap.put("allowApproveOperate", "1".equals(allowApproveOperate));
        msgMap.put("commandResult", "1".equals(commandResult));

        Map<String, Object> headers = new HashMap<>(2);
        headers.put("TAGS", "in");
        MessageHeaders messageHeaders = new MessageHeaders(headers);
        Message<Map<String, Object>> message = MessageBuilder.createMessage(msgMap, messageHeaders);
        System.out.println(JSONObject.toJSON(message));
        mySource.channelSendMessage().send(message);
        logger.info("模仿渠道端发送消息=========================End");
        return "success";
    }

    @GetMapping("/sendTrek")
    public boolean sendTrek() {
        // <2>创建 Message
        Demo01Message message = new Demo01Message().setId(new Random().nextInt());
        // <3>创建 Spring Message 对象
        Message<Demo01Message> springMessage = MessageBuilder.withPayload(message).build();
        // <4>发送消息
        return mySource.trekOutput().send(springMessage);
    }

    @GetMapping("/send_delay")
    public boolean sendDelay() {
        // 创建 Message
        Demo01Message message = new Demo01Message().setId(new Random().nextInt());
        // 创建 Spring Message 对象
        Message<Demo01Message> springMessage = MessageBuilder.withPayload(message)
                .setHeader(MessageConst.PROPERTY_DELAY_TIME_LEVEL, "3") // 设置延迟级别为 3，10 秒后消费。
                .build();
        // 发送消息
        boolean sendResult = mySource.erbadagangOutput().send(springMessage);
        logger.info("[sendDelay][发送消息完成, 结果 = {}]", sendResult);
        return sendResult;
    }

    /**
     * 发送带有3个tag的message
     *
     * @return
     */
    @GetMapping("/send_tag")
    public boolean sendTag() {
        for (String tag : new String[]{"trek", "specialized", "look"}) {
            // 创建 Message
            Demo01Message message = new Demo01Message().setId(new Random().nextInt());
            // 创建 Spring Message 对象
            Message<Demo01Message> springMessage =
                    MessageBuilder.withPayload(message).setHeader(MessageConst.PROPERTY_TAGS, tag) // 设置 Tag
                            .setHeader(MessageConst.PROPERTY_KEYS, tag) // 设置 key，方便在控制台查找。
                            .build();
            // 发送消息
            mySource.erbadagangOutput().send(springMessage);
        }
        return true;
    }

}
